package com.rfzn.mynfc

import java.text.NumberFormat
import kotlin.math.pow

object HexUtils {

    fun hexStringToDecimal(hex: String): String {

        val kv = HashMap<Char, Int>()
        kv['0'] = 0
        kv['1'] = 1
        kv['2'] = 2
        kv['3'] = 3
        kv['4'] = 4
        kv['5'] = 5
        kv['6'] = 6
        kv['7'] = 7
        kv['8'] = 8
        kv['9'] = 9
        kv['A'] = 10
        kv['B'] = 11
        kv['C'] = 12
        kv['D'] = 13
        kv['E'] = 14
        kv['F'] = 15

        var sum = 0.0

        run breaking@{
            hex.forEachIndexed { index, c ->
                println("c=${c}")
                if (kv.containsKey(c)) {
                    val avg = kv.getValue(c) * 16.0.pow((hex.length - (index + 1)).toDouble())
                    println("${kv.getValue(c)}*16^${hex.length - (index + 1)}=${avg}")
                    sum += avg
                } else {
                    sum = 0.0
                    return@breaking
                }
            }
        }
        if (sum == 0.0) {
            return ""
        }

        val instance = NumberFormat.getInstance()
        instance.isGroupingUsed = false //设置不使用科学计数器
        instance.maximumFractionDigits = 0 //小数点最大位数

        return instance.format(sum)
    }



    fun flipHexStr(s: String): String {
        val result = StringBuilder()
        var i = 0
        while (i <= s.length - 2) {
            result.append(StringBuilder(s.substring(i, i + 2)).reverse())
            i += 2
        }
        return result.reverse().toString()
    }


    // bytes转16进制
    fun bytesToHexString(byte: ByteArray): String {
        var i: Int
        var e: Int
        val hex = arrayOf(
            "0",
            "1",
            "2",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8",
            "9",
            "A",
            "B",
            "C",
            "D",
            "E",
            "F"
        )
        val out = StringBuilder()
        var j = 0
        while (j < byte.size) {
            e = byte[j].toInt() and 0xff
            i = e shr 4 and 0x0f
            out.append(hex[i])
            i = e and 0x0f
            out.append(hex[i])
            ++j
        }
        return out.toString()
    }

}